package com.david.jetpack.datastore

import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

//参考链接：https://developer.android.google.cn/topic/libraries/architecture/datastore?hl=zh-cn
class DataStoreTestActivity: AppCompatActivity() {
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        CoroutineScope(Dispatchers.IO).launch {
            dataStore.edit { settings ->
                val currentCounterValue = settings[intPreferencesKey("example_counter")
                ] ?: 0
                settings[intPreferencesKey("example_counter")] = currentCounterValue + 1
            }
        }

    }
}